<template>
  <view class="container">
    <text class="title">{{ title }}</text>
    <canvas
      canvas-id="gestureCanvas"
      :style="{ width: `${width}px`, height: `${height}px` }"
      @touchstart="onTouchStart"
      @touchmove="onTouchMove"
      @touchend="onTouchEnd"
    />
    <text class="tip">{{ tipText }}</text>
    <button v-if="status === 'confirm'" @click="reset" style="margin-top: 20px;">
      重新设置
    </button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      width: 300,
      height: 300,
      cellSize: 80,
      radius: 10,
      margin: 30,
      points: [],
      result: [],
      status: 'init', // init, setting, confirming, verifying
      savedPassword: '',
      title: '手势密码登录',
      tipText: '请绘制手势密码',
      isDrawing: false,
      startX: 0,
      startY: 0,
    };
  },

  onLoad() {
    // 检查是否已设置过密码
    const pwd = uni.getStorageSync('gesture_password');
    if (pwd) {
      this.savedPassword = pwd;
      this.status = 'verifying';
      this.title = '请输入手势密码';
      this.tipText = '请输入已设置的手势密码';
    } else {
      this.status = 'init';
      this.startSetup();
    }

    // 获取 Canvas 尺寸
    const info = uni.createSelectorQuery().select('#gestureCanvas');
    info.boundingClientRect();
    info.exec((res) => {
      if (res && res[0]) {
        this.width = res[0].width;
        this.height = res[0].height;
        this.initPoints();
        this.drawCircles();
      }
    });
  },

  methods: {
    initPoints() {
      const { width, margin, cellSize } = this;
      const offset = (width - cellSize * 3) / 2;
      const points = [];
      for (let i = 0; i < 3; i++) {
        for (let j = 0; j < 3; j++) {
          points.push({
            x: offset + j * cellSize + cellSize / 2,
            y: offset + i * cellSize + cellSize / 2,
            index: i * 3 + j,
          });
        }
      }
      this.points = points;
    },

    drawCircles() {
      const ctx = uni.createCanvasContext('gestureCanvas', this);
      ctx.clearRect(0, 0, this.width, this.height);

      this.points.forEach(pt => {
        ctx.beginPath();
        ctx.arc(pt.x, pt.y, this.radius, 0, Math.PI * 2);
        ctx.fillStyle = '#c0c0c0';
        ctx.fill();
      });

      ctx.draw();
    },

    getTouchedPoint(x, y) {
      return this.points.find(pt => {
        const dx = pt.x - x;
        const dy = pt.y - y;
        return Math.sqrt(dx * dx + dy * dy) < this.radius + 10;
      });
    },

    onTouchStart(e) {
      if (this.isDrawing) return;
      const { clientX, clientY } = e.touches[0];
      const point = this.getTouchedPoint(clientX, clientY);
      if (point) {
        this.isDrawing = true;
        this.result = [point.index];
        this.startX = clientX;
        this.startY = clientY;

        const ctx = uni.createCanvasContext('gestureCanvas', this);
        ctx.clearRect(0, 0, this.width, this.height);

        this.points.forEach(p => {
          ctx.beginPath();
          ctx.arc(p.x, p.y, this.radius, 0, Math.PI * 2);
          ctx.fillStyle = p.index === point.index ? '#409eff' : '#c0c0c0';
          ctx.fill();
        });

        this.$nextTick(() => {
          ctx.draw();
        });
      }
    },

    onTouchMove(e) {
      if (!this.isDrawing) return;
      const { clientX, clientY } = e.touches[0];
      const currentPoint = this.getTouchedPoint(clientX, clientY);

      const ctx = uni.createCanvasContext('gestureCanvas', this);
      ctx.clearRect(0, 0, this.width, this.height);

      // 重绘所有圆圈
      this.points.forEach(p => {
        const isSelected = this.result.includes(p.index);
        ctx.beginPath();
        ctx.arc(p.x, p.y, this.radius, 0, Math.PI * 2);
        ctx.fillStyle = isSelected ? '#409eff' : '#c0c0c0';
        ctx.fill();
      });

      // 绘制已连接的线
      if (this.result.length > 0) {
        ctx.beginPath();
        ctx.moveTo(this.points[this.result[0]].x, this.points[this.result[0]].y);
        for (let i = 1; i < this.result.length; i++) {
          const pt = this.points[this.result[i]];
          ctx.lineTo(pt.x, pt.y);
        }
        ctx.strokeStyle = '#409eff';
        ctx.lineWidth = 4;
        ctx.stroke();
      }

      // 绘制当前拖动的线
      ctx.beginPath();
      let lastPt = this.points[this.result[this.result.length - 1]];
      ctx.moveTo(lastPt.x, lastPt.y);
      ctx.lineTo(clientX, clientY);
      ctx.strokeStyle = '#409eff';
      ctx.lineWidth = 4;
      ctx.stroke();

      ctx.draw();

      // 添加新点
      if (currentPoint && !this.result.includes(currentPoint.index)) {
        this.result.push(currentPoint.index);
      }
    },

    onTouchEnd() {
      if (!this.isDrawing) return;
      this.isDrawing = false;

      const password = this.result.join('');

      if (this.status === 'setting') {
        if (password.length < 4) {
          this.tipText = '手势至少连接4个点，请重试';
          this.resetCanvas();
          return;
        }
        uni.setStorageSync('temp_gesture', password);
        this.status = 'confirm';
        this.tipText = '请再次绘制确认手势';
        this.resetCanvas();

      } else if (this.status === 'confirm') {
        const temp = uni.getStorageSync('temp_gesture');
        if (password === temp) {
          uni.setStorageSync('gesture_password', password);
          this.savedPassword = password;
          uni.showToast({ title: '设置成功', icon: 'success' });
          this.status = 'verifying';
          this.title = '登录成功！';
          this.tipText = '手势密码已设置并登录';
        } else {
          this.tipText = '两次不一致，请重新设置';
          this.status = 'init';
          this.$nextTick(() => {
            this.startSetup();
          });
        }

      } else if (this.status === 'verifying') {
        if (password === this.savedPassword) {
          uni.showToast({ title: '登录成功', icon: 'success' });
          this.tipText = '登录成功！';
          // 这里跳转主页或触发登录逻辑
          // uni.reLaunch({ url: '/pages/index/index' });
        } else {
          this.tipText = '密码错误，请重试';
          setTimeout(() => {
            this.resetCanvas();
          }, 500);
        }
      }
    },

    startSetup() {
      this.status = 'setting';
      this.title = '设置手势密码';
      this.tipText = '请绘制至少4个点的手势';
      this.resetCanvas();
    },

    reset() {
      uni.removeStorageSync('temp_gesture');
      uni.removeStorageSync('gesture_password');
      this.savedPassword = '';
      this.status = 'init';
      this.startSetup();
    },

    resetCanvas() {
      const ctx = uni.createCanvasContext('gestureCanvas', this);
      ctx.clearRect(0, 0, this.width, this.height);
      this.points.forEach(pt => {
        ctx.beginPath();
        ctx.arc(pt.x, pt.y, this.radius, 0, Math.PI * 2);
        ctx.fillStyle = '#c0c0c0';
        ctx.fill();
      });
      ctx.draw();
    },
  },
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40rpx;
  background-color: #f8f8f8;
  height: 100vh;
}

title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
}

canvas {
  border: 1px dashed #ddd;
  border-radius: 10px;
  background-color: #fff;
  margin: 40rpx 0;
}

.tip {
  color: #666;
  font-size: 28rpx;
  margin-top: 20rpx;
}
</style>